<template>
  <div class="zy-content">
    <search
      :columns="searchData"
      @getSearch="getSearch(arguments)"
      key="search"
      ref="searchCom"
      @reset="reset"
    ></search>
    <div class="alarmConfiguration">
      <!-- 生产订单-->
      <div class="list-layout mt16">
        <!-- 批量删除 批量导出  批量导入 下载模板 新增-->
        <div class="btns clear">
          <span class="title">工单任务</span>
          <Button type="primary"  class="search-btn" @click="jumpAdd">新建</Button>
          <Button type="primary" @click="issue">确认并下发</Button>
          <Dropdown @on-click="dropDownSelect">
            <Button type="primary">
              更多
              <Icon type="ios-arrow-down"></Icon>
            </Button>
            <template #list>
              <DropdownMenu>
                <DropdownItem name="export">导出</DropdownItem>
                <DropdownItem name="completed">强制完工</DropdownItem>
                <DropdownItem name="close">关闭</DropdownItem>
              </DropdownMenu>
            </template>
          </Dropdown>
        </div>
        <!-- 表格 -->
        <div class="tableContent">
          <Table
            class="resizable-table"
            border
            size="small"
            highlight-row
            @on-column-width-resize="onColumnWidthResize"
            :columns="columns"
            @on-selection-change="onSelectChange"
            ellipsis
            ref="selection"
            stripe
            :data="dataArr"
            @on-row-dblclick="seeDetail"
          >
            <template #planStatus="{ row, index }">
              <span v-if="row.planStatus === 0">新建</span>
              <span v-else-if="row.planStatus === 1">已下发</span>
              <span v-else-if="row.planStatus === 2">已排程</span>
              <span v-else-if="row.planStatus === 3">已派工</span>
              <span v-else-if="row.planStatus === 4">生产中</span>
              <span v-else-if="row.planStatus === 5">已完工</span>
              <span v-else-if="row.planStatus === 6">已暂停</span>
              <span v-else-if="row.planStatus === 7">关闭</span>
              <span v-else>关闭</span>
            </template>
            <template #planType="{ row, index }">
              <span v-if="row.planType === 1">正常</span>
              <span v-else>返工</span>
            </template>
            <template #directDistribution="{ row, index }">
              <span v-if="row.directDistribution === 1">是</span>
              <span v-else>否</span>
            </template>
            <template #samePlanCardControl="{ row, index }">
              <span v-if="row.samePlanCardControl === 1">是</span>
              <span v-else>否</span>
            </template>
            <template #action="{ row, index }">
              <span class="editBtn" @click="seeDetail(row)">编辑</span>
            </template>
          </Table>
        </div>
        <!-- 分页 -->
        <div class="pageWrap mt16">
          <pageLeftTitle :total="total" :selected="selection.length" />
          <Page
            :total="total"
            :page-size="pageSize"
            :current="pageNum"
            @on-change="changePageNum"
            @on-page-size-change="changePageSize"
            show-sizer
            show-total
          />
        </div>
      </div>
      <Modal v-model="modal" title="关闭工单任务">
        <Input
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 3 }"
            :maxlength="200"
            v-model="reason"
            placeholder="请输入关闭原因"
        />
        <div slot="footer">
          <Button @click="modal = false">取消</Button>
          <Button type="primary" @click="sureClose">确认</Button>
        </div>
      </Modal>
    </div>
  </div>
</template>

<script>
import {
  closePlan,
  completedPlan,
  exportPlan, issuePlan,
  planList,
} from "@/api/planManage/productionPlan.js";
import search from "@/components/curd/searchList.vue";
import toggleTableOperation from "@/mixins/toggleTableOperation";
export default {
  name: "productionPlan",
  components: { search },
  mixins: [toggleTableOperation],
  data() {
    return {
      currentRow: null,
      selection: [],
      searchData: [
        {
          title: "生产订单号",
          key: "planNo",
        },
        {
          title: "计划状态",
          key: "status",
          type: "select",
          dicUrl: "/dms/common/productionPlanStateList",
          params: {
            label: "desc",
            value: "code",
          },
          // dicData: [
          //   { label: "新建", value: 0},
          //   { label: "已下发", value: 1 },
          //   { label: "已排程", value: 2 },
          //   { label: "已派工", value: 3 },
          //   { label: "生产中", value: 4 },
          //   { label: "已完工", value: 5 },
          //   { label: "已暂停", value: 6 },
          //   { label: "关闭", value: 7 },
          // ],
        },
        {
          title: "计划类型",
          key: "planType",
          type: "select",
          dicData: [
            { label: "正常", value: 1 },
            { label: "返工", value: 2 }
          ],
        },
        {
          title: "物料编码",
          key: "materialCode",
        },
        {
          title: "车间产线",
          key: "lineId",
          type: "cascader",
          dicUrl: "/basic/organization/findListByToken?level=0",
          params: {
            label: "name",
            value: "id",
            children: "children"
          }
        },
        {
          title: "BOM版本号",
          key: "bomVersion",
        },
        {
          title: "创建人",
          key: "crtUserId",
          type: 'search',
          dicUrl: '/dms/user/userList',
          queryName: 'key',
          resultParams: 'res.data',
          params: {
            label: 'realname',
            value: 'id',
          },
        },
        {
          title: "创建时间",
          key: "time",
          noreset: true,
          defaultTimeRange:30,
          format: 'yyyy-MM-dd HH:mm:ss',
          type: "datetimerange",
          pushDay:true,
        }
      ],
      columns: [
        {
          key: "selection",
          type: "selection",
          width: 60,
          align: "center",
        },
        {
          title: "生产订单号",
          key: "planNo",
          minWidth: 130,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "计划状态",
          key: "planStatus",
          slot: "planStatus",
          minWidth: 130,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "计划类型",
          key: "planType",
          slot: "planType",
          minWidth: 130,
          align: "center",
          resizable: true,
          tooltip: true,
        },

        {
          title: "计划数量",
          key: "materialQty",
          width: 130,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "物料编码",
          key: "materialCode",
          width: 200,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "计划开始时间",
          key: "startTime",
          minWidth: 170,
          align: "center",
          resizable: true,
          tooltip: true
        },
        {
          title: "计划结束时间",
          key: "endTime",
          width: 170,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "BOM版本号",
          key: "version",
          width: 130,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "物料版本",
          key: "materialEdition",
          width: 100,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "直接下发",
          key: "directDistribution",
          slot: "directDistribution",
          width: 100,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "是否同计划卡控",
          key: "samePlanCardControl",
          slot: "samePlanCardControl",
          width: 140,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "车间产线",
          key: "productionLineName",
          width: 170,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "关闭人",
          key: "closeName",
          minWidth: 100,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "关闭时间",
          key: "closeDate",
          width: 170,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "关闭原因",
          key: "closeReason",
          width: 170,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "备注",
          key: "memo",
          width: 130,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "创建人名称",
          key: "crtUserName",
          width: 130,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "创建时间",
          key: "crtTime",
          width: 170,
          defaultTimeRange:30,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "更新人名称",
          key: "updateUserName",
          minWidth: 130,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "更新时间",
          key: "updateTime",
          minWidth: 170,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "操作",
          slot: "action",
          fixed: "right",
          minWidth: 100,
          align: "center"
        }
      ],
      searchParams: {},
      pageNum: 1,
      pageSize: 10,
      total: 0,
      dataArr: [],
      modal: false,
      reason: ''
    };
  },
  mounted() {
    this.getTableColumnsWidth(this.columns);
    this.$refs.searchCom.changeNum()
  },
  methods: {
    onSelectChange(selection) {
      let myArray = [];
      selection.map((item) => {
        myArray.push(item);
      });
      this.selection = myArray;
    },
    getSearch(info) {
      let result = JSON.parse(JSON.stringify(info[0])) || {};
      this.searchParams = {
        bomVersion: result.bomVersion,
        crtUserId: result.crtUserId,
        customMaterialCode: result.customMaterialCode,
        materialCode: result.materialCode,
        planNo: result.planNo,
        planType: result.planType,
        status: result.status,
        lineId: result.lineId ? result.lineId[result.lineId.length - 1] : ''
      }
      if (result.time && result.time.length === 2) {
        this.searchParams.startTime = result.time[0];
        this.searchParams.endTime = result.time[1];
      }
      this.pageNum = 1;
      this.searchList();
    },
    changeNum(data) {
      this.pageNum = 1;
      this.searchParams = data;
      this.searchList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.searchList();
    },
    changePageNum(val) {
      this.pageNum = val;
      this.searchList();
    },
    //查询列表
    searchList() {
      this.selection = [];
      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      };
      for (let key in this.searchParams) {
        if (this.searchParams[key] || this.searchParams[key] === 0) {
          this.$set(params, key, this.searchParams[key]);
        }
      }
      planList(params).then(res => {
        if(res.code === 200){
          let { data = {}} = res || {};
          this.dataArr =  data.list || [];
          this.total = data.total || 0;
        } else {
          this.$Message.warning({content: res.msg})
        }
      })
    },
    reset() {
      this.selection = []
    },
    jumpAdd () {
      this.$router.push('/planManage/productionPlan/add')
    },
    seeDetail(info){
      this.$router.push('/planManage/productionPlan/add?id=' + info.id)
    },
    dropDownSelect(type){
      if(type === 'export'){
       this.exportFile()
      } else if (type === 'completed'){
        this.complete()
      } else if(type === 'close'){
        this.planClose()
      }
    },
    exportFile(){
      let params = {};
      for (let key in this.searchParams) {
        if (this.searchParams[key]) {
          this.$set(params, key, this.searchParams[key]);
        }
      }
      exportPlan(params).then(res => {
        const blob = res.data;
        let arr = decodeURIComponent(res.headers['content-disposition']).split('filename=')
        let fileName = arr[arr.length - 1];
        if (blob.size < 200 && blob.type && blob.type.includes('json')) {
          let reader = new FileReader();
          reader.readAsText(blob, "utf-8");
          let result;
          reader.onload = () => {
            try {
              result = JSON.parse(reader.result);
            } catch (e) {
              result = null;
            }
            if (result.msg) { // 下载失败
              this.$Message.warning({content: result.msg})
            } else {
              this.downloadFile(blob, fileName)
            }
          }
        } else {
          this.downloadFile(blob, fileName)
        }
      })
    },
    downloadFile(blob, fileName) {
      const tmpLink = document.createElement("a");
      const objectUrl = URL.createObjectURL(blob);
      tmpLink.href = objectUrl;
      tmpLink.download = fileName;
      tmpLink.click();
      window.URL.revokeObjectURL(objectUrl);
    },
    complete(){
      if(this.selection.length === 0){
        this.$Message.warning({content: '请选择工单'})
        return
      }
      let ids = [];
      let check = this.selection.some(val => {
        ids.push(val.id)
        if (val.planStatus !== 2 && val.planStatus !== 1) {
          return true
        }
        return false
      })
      if(check){
        this.$Message.warning({content: '强制完工操作只能选择已排程状态和已下发状态的工单'})
        return;
      }
      completedPlan(ids).then(res => {
        if(res.code === 200){
          this.$Message.success({content: '强制完工操作成功'})
          this.searchList();
        } else {
          this.$Message.warning({content: res.msg})
        }
      })
    },
    planClose() {
      if(this.selection.length === 0){
        this.$Message.warning({content: '请选择工单'})
        return
      }
      let ids = [];
      let check = this.selection.some(val => {
        ids.push(val.id)
        if (val.planStatus !== 0 && val.planStatus !== 1) {
          return true
        }
        return false
      })
      if(check){
        this.$Message.warning({content: '关闭操作只能选择新建状态和已下发状态的工单'})
        return;
      }
      this.reason = '';
      this.modal = true
    },
    sureClose(){
      if(this.selection.length === 0){
        this.$Message.warning({content: '请选择工单'})
        return
      }
      let ids = [];
      let check = this.selection.some(val => {
        ids.push(val.id)
        if (val.planStatus !== 0 && val.planStatus !== 1) {
          return true
        }
        return false
      })
      if(check){
        this.$Message.warning({content: '关闭操作只能选择新建状态和已下发状态的工单'})
        return;
      }
      if(!this.reason){
        this.$Message.warning({content: '请输入关闭理由'})
        return;
      }
      closePlan({
        planIdList: ids,
        reason: this.reason
      }).then(res => {
        if(res.code === 200){
          this.$Message.success({content: '关闭成功'})
          this.modal = false;
          this.searchList();
        } else {
          this.$Message.warning({content: res.msg})
        }
      })
    },
    issue(){
      if(this.selection.length === 0){
        this.$Message.warning({content: '请选择工单'})
        return
      }
      let ids = [];
      let check = this.selection.some(val => {
        ids.push(val.id)
        if(val.planStatus !== 0) {
          return true
        }
        return false
      })
      if(check){
        this.$Message.warning({content: '下发操作只能选择新建状态的工单'})
        return;
      }
      issuePlan({planIdList: ids}).then(res => {
        if(res.code === 200){
          this.$Message.success({content: '下发成功'})
          this.searchList();
        } else {
          this.$Message.warning({content: res.msg})
        }
      })
    }
  },
};
</script>

<style scoped lang="scss">
.echatone {
  width: 100%;
  height: 320px;
  display: flex;

  .echattwo {
    height: 100%;
    width: 40%;
  }

  .echatthree {
    height: 100%;
    width: 60%;
  }
}
.editBtn{
  color: #035beb;
  cursor: pointer;
}
.btns{
  i{
    font-size: 14px;
    color: #ffffff;
  }
  .ivu-dropdown-item{
    text-align: center;
  }
}
</style>

